// 数据查询页面

let dataQueryData = [];
let filteredData = [];

// 加载数据查询页面
function loadDataQueryPage(container) {
    container.innerHTML = `
        ${createPageTitle('数据查询', 'fas fa-search')}
        ${createToolbar([
            '<button class="btn btn-primary" onclick="showAddDataQueryModal()">',
            '<i class="fas fa-plus mr-2"></i>新增数据',
            '</button>',
            '<button class="btn btn-secondary" onclick="loadDataQueryData()">',
            '<i class="fas fa-refresh mr-2"></i>刷新',
            '</button>',
            '<button class="btn btn-accent" onclick="exportDataQueryData()">',
            '<i class="fas fa-download mr-2"></i>导出',
            '</button>'
        ])}
        <div id="data-query-list">
            ${createDataQueryTable()}
        </div>
    `;
    
    // 绑定搜索事件
    const searchInput = document.getElementById('search-input');
    if (searchInput) {
        searchInput.addEventListener('input', debounce(handleDataQuerySearch, 300));
    }
    
    // 加载数据
    loadDataQueryData();
}

// 创建数据查询表格
function createDataQueryTable() {
    const headers = ['工单号', '工单分类', '品号', '品名', '规格', '分类', '工单数', '版本', '生产日期', '工序', '钢网TOP', '钢网BOT', '回流焊治具', '波峰焊治具', '压接治具', 'BOM', 'SOP', '生产资料', '类型'];
    
    return `
        <div class="table-container">
            <table class="table table-zebra w-full">
                <thead>
                    <tr>
                        ${headers.map(header => `<th>${header}</th>`).join('')}
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    ${filteredData.map(item => `
                        <tr>
                            <td>${item.workOrder || '-'}</td>
                            <td>${item.workOrderType || '-'}</td>
                            <td>${item.partNumber || '-'}</td>
                            <td>${item.partName || '-'}</td>
                            <td>${item.specification || '-'}</td>
                            <td>${item.category || '-'}</td>
                            <td>${item.workOrderQuantity || '-'}</td>
                            <td>${item.version || '-'}</td>
                            <td>${item.productionDate || '-'}</td>
                            <td>${item.process || '-'}</td>
                            <td>${createStatusButton(item, 'steelMeshTop')}</td>
                            <td>${createStatusButton(item, 'steelMeshBot')}</td>
                            <td>${createStatusButton(item, 'reflowFixture')}</td>
                            <td>${createStatusButton(item, 'waveFixture')}</td>
                            <td>${createStatusButton(item, 'pressFixture')}</td>
                            <td>${createStatusButton(item, 'bom')}</td>
                            <td>${createStatusButton(item, 'sop')}</td>
                            <td>${createStatusButton(item, 'productionData')}</td>
                            <td>${item.type || '-'}</td>
                            <td>
                                <div class="btn-group">
                                    <button class="btn btn-sm btn-primary" onclick="editDataQuery('${item.id}')">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <button class="btn btn-sm btn-error" onclick="deleteDataQuery('${item.id}')">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>
                            </td>
                        </tr>
                    `).join('')}
                </tbody>
            </table>
        </div>
    `;
}

// 创建状态按钮
function createStatusButton(item, statusType) {
    const status = item[statusType];
    const buttonClass = status === 'check' ? 'status-btn check' : 'status-btn cross';
    const icon = status === 'check' ? 'check' : 'times';
    const text = status === 'check' ? '√' : '×';
    
    return `
        <button class="${buttonClass}" onclick="toggleStatus('${item.id}', '${statusType}')">
            <i class="fas fa-${icon}"></i> ${text}
        </button>
    `;
}

// 切换状态
async function toggleStatus(id, statusType) {
    try {
        const item = dataQueryData.find(d => d.id === id);
        if (!item) return;
        
        const currentStatus = item[statusType];
        const newStatus = currentStatus === 'check' ? 'cross' : 'check';
        
        await dataQueryAPI.updateStatus(id, statusType, newStatus);
        
        // 更新本地数据
        item[statusType] = newStatus;
        updateDataQueryTable();
        
        showSuccess('状态更新成功');
    } catch (error) {
        showError('状态更新失败');
    }
}

// 加载数据查询数据
async function loadDataQueryData() {
    try {
        const data = await dataQueryAPI.getAll();
        dataQueryData = data;
        filteredData = data;
        updateDataQueryTable();
    } catch (error) {
        showError('加载数据失败');
    }
}

// 更新数据查询表格
function updateDataQueryTable() {
    const tableContainer = document.getElementById('data-query-list');
    if (tableContainer) {
        tableContainer.innerHTML = createDataQueryTable();
    }
}

// 处理搜索
function handleDataQuerySearch() {
    const query = document.getElementById('search-input')?.value?.trim() || '';
    
    if (!query) {
        filteredData = dataQueryData;
    } else {
        filteredData = dataQueryData.filter(item => 
            item.workOrder?.toLowerCase().includes(query.toLowerCase()) ||
            item.partNumber?.toLowerCase().includes(query.toLowerCase()) ||
            item.partName?.toLowerCase().includes(query.toLowerCase()) ||
            item.model?.toLowerCase().includes(query.toLowerCase())
        );
    }
    
    updateDataQueryTable();
}

// 显示新增模态框
function showAddDataQueryModal() {
    const content = `
        <form id="data-query-form" class="space-y-4">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                ${createFormInput('工单号', 'workOrder', 'text', '', { required: true })}
                ${createFormInput('工单分类', 'workOrderType', 'text', '')}
                ${createFormInput('品号', 'partNumber', 'text', '', { required: true })}
                ${createFormInput('品名', 'partName', 'text', '', { required: true })}
                ${createFormInput('规格', 'specification', 'text', '')}
                ${createFormInput('分类', 'category', 'text', '')}
                ${createFormInput('工单数', 'workOrderQuantity', 'number', '', { required: true })}
                ${createFormInput('版本', 'version', 'text', '')}
                ${createFormInput('生产日期', 'productionDate', 'date', '')}
                ${createFormInput('工序', 'process', 'text', '')}
                ${createFormInput('类型', 'type', 'text', '')}
            </div>
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div>
                    <label class="form-label">钢网TOP</label>
                    <select class="select select-bordered w-full" name="steelMeshTop">
                        <option value="cross">×</option>
                        <option value="check">√</option>
                    </select>
                </div>
                <div>
                    <label class="form-label">钢网BOT</label>
                    <select class="select select-bordered w-full" name="steelMeshBot">
                        <option value="cross">×</option>
                        <option value="check">√</option>
                    </select>
                </div>
                <div>
                    <label class="form-label">回流焊治具</label>
                    <select class="select select-bordered w-full" name="reflowFixture">
                        <option value="cross">×</option>
                        <option value="check">√</option>
                    </select>
                </div>
                <div>
                    <label class="form-label">波峰焊治具</label>
                    <select class="select select-bordered w-full" name="waveFixture">
                        <option value="cross">×</option>
                        <option value="check">√</option>
                    </select>
                </div>
                <div>
                    <label class="form-label">压接治具</label>
                    <select class="select select-bordered w-full" name="pressFixture">
                        <option value="cross">×</option>
                        <option value="check">√</option>
                    </select>
                </div>
                <div>
                    <label class="form-label">BOM</label>
                    <select class="select select-bordered w-full" name="bom">
                        <option value="cross">×</option>
                        <option value="check">√</option>
                    </select>
                </div>
                <div>
                    <label class="form-label">SOP</label>
                    <select class="select select-bordered w-full" name="sop">
                        <option value="cross">×</option>
                        <option value="check">√</option>
                    </select>
                </div>
                <div>
                    <label class="form-label">生产资料</label>
                    <select class="select select-bordered w-full" name="productionData">
                        <option value="cross">×</option>
                        <option value="check">√</option>
                    </select>
                </div>
            </div>
        </form>
    `;
    
    showModal('新增数据查询', content, () => {
        const form = document.getElementById('data-query-form');
        if (form.checkValidity()) {
            const formData = new FormData(form);
            const data = {};
            
            // 收集所有表单数据
            for (let [key, value] of formData.entries()) {
                data[key] = value;
            }
            
            createDataQuery(data);
        } else {
            form.reportValidity();
        }
    });
    
    // 重新绑定表单提交事件
    setTimeout(() => {
        const modal = document.querySelector('.modal');
        const confirmBtn = modal.querySelector('.btn-primary');
        confirmBtn.onclick = () => {
            const form = document.getElementById('data-query-form');
            if (form.checkValidity()) {
                const formData = new FormData(form);
                const data = {};
                
                for (let [key, value] of formData.entries()) {
                    data[key] = value;
                }
                
                createDataQuery(data);
                modal.remove();
            } else {
                form.reportValidity();
            }
        };
    }, 100);
}

// 创建数据查询
async function createDataQuery(data) {
    try {
        await dataQueryAPI.create(data);
        showSuccess('创建成功');
        loadDataQueryData();
    } catch (error) {
        showError('创建失败');
    }
}

// 编辑数据查询
function editDataQuery(id) {
    const item = dataQueryData.find(d => d.id === id);
    if (!item) {
        showError('记录不存在');
        return;
    }
    
    const content = `
        <form id="data-query-edit-form" class="space-y-4">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                ${createFormInput('工单号', 'workOrder', 'text', item.workOrder, { required: true })}
                ${createFormInput('工单分类', 'workOrderType', 'text', item.workOrderType)}
                ${createFormInput('品号', 'partNumber', 'text', item.partNumber, { required: true })}
                ${createFormInput('品名', 'partName', 'text', item.partName, { required: true })}
                ${createFormInput('规格', 'specification', 'text', item.specification)}
                ${createFormInput('分类', 'category', 'text', item.category)}
                ${createFormInput('工单数', 'workOrderQuantity', 'number', item.workOrderQuantity, { required: true })}
                ${createFormInput('版本', 'version', 'text', item.version)}
                ${createFormInput('生产日期', 'productionDate', 'date', item.productionDate)}
                ${createFormInput('工序', 'process', 'text', item.process)}
                ${createFormInput('类型', 'type', 'text', item.type)}
            </div>
        </form>
    `;
    
    showModal('编辑数据查询', content, () => {
        const form = document.getElementById('data-query-edit-form');
        if (form.checkValidity()) {
            const formData = new FormData(form);
            const data = {};
            
            for (let [key, value] of formData.entries()) {
                data[key] = value;
            }
            
            updateDataQuery(id, data);
        } else {
            form.reportValidity();
        }
    });
    
    // 重新绑定表单提交事件
    setTimeout(() => {
        const modal = document.querySelector('.modal');
        const confirmBtn = modal.querySelector('.btn-primary');
        confirmBtn.onclick = () => {
            const form = document.getElementById('data-query-edit-form');
            if (form.checkValidity()) {
                const formData = new FormData(form);
                const data = {};
                
                for (let [key, value] of formData.entries()) {
                    data[key] = value;
                }
                
                updateDataQuery(id, data);
                modal.remove();
            } else {
                form.reportValidity();
            }
        };
    }, 100);
}

// 更新数据查询
async function updateDataQuery(id, data) {
    try {
        await dataQueryAPI.update(id, data);
        showSuccess('更新成功');
        loadDataQueryData();
    } catch (error) {
        showError('更新失败');
    }
}

// 删除数据查询
function deleteDataQuery(id) {
    showConfirmDialog('确定要删除这条记录吗？', async () => {
        try {
            await dataQueryAPI.delete(id);
            showSuccess('删除成功');
            loadDataQueryData();
        } catch (error) {
            showError('删除失败');
        }
    });
}

// 导出数据查询数据
function exportDataQueryData() {
    if (filteredData.length === 0) {
        showWarning('没有数据可导出');
        return;
    }
    
    const exportData = filteredData.map(item => ({
        '工单号': item.workOrder,
        '工单分类': item.workOrderType,
        '品号': item.partNumber,
        '品名': item.partName,
        '规格': item.specification,
        '分类': item.category,
        '工单数': item.workOrderQuantity,
        '版本': item.version,
        '生产日期': item.productionDate,
        '工序': item.process,
        '钢网TOP': item.steelMeshTop === 'check' ? '√' : '×',
        '钢网BOT': item.steelMeshBot === 'check' ? '√' : '×',
        '回流焊治具': item.reflowFixture === 'check' ? '√' : '×',
        '波峰焊治具': item.waveFixture === 'check' ? '√' : '×',
        '压接治具': item.pressFixture === 'check' ? '√' : '×',
        'BOM': item.bom === 'check' ? '√' : '×',
        'SOP': item.sop === 'check' ? '√' : '×',
        '生产资料': item.productionData === 'check' ? '√' : '×',
        '类型': item.type
    }));
    
    exportToCSV(exportData, `数据查询_${formatDate(new Date(), 'YYYY-MM-DD')}.csv`);
    showSuccess('导出成功');
}

// 绑定到全局作用域
window.loadDataQueryPage = loadDataQueryPage;
window.showAddDataQueryModal = showAddDataQueryModal;
window.editDataQuery = editDataQuery;
window.deleteDataQuery = deleteDataQuery;
window.exportDataQueryData = exportDataQueryData;
window.toggleStatus = toggleStatus;
